package dsx.system;

public abstract class ThreadEx extends Thread {

	boolean stop = true;
	boolean running = false;
	int interval = 0;

	public ThreadEx() {
		super();
	}

	public ThreadEx(ThreadGroup group, Runnable target, String name,
				  long stackSize) {
		super(group, target, name, stackSize);
	}

	public static void sleepEx(int milliseconds) {
		try {
			Thread.sleep(milliseconds);
		} catch (Exception ex) {

		}
	}

	public void waitEx(int milliseconds) {
		try {
			synchronized (this) {
				this.wait(milliseconds);
			}
		} catch (Exception ex) {

		}
	}

	public void notifyEx() {
		synchronized (this) {
			this.notify();
		}
	}

	public void setInterval(int interval) {
		this.interval = interval;
	}

	@Override
	public void start() {
		this.stop = false;
		super.start();
	}

	public void stopEx() {
		this.stop = true;
		while (this.running) {
			sleepEx(100);
		}
	}

	void stopExAsync() {
		this.stop = true;
	}

	@Override
	public void run() {
		this.running = true;
		while (!this.stop) {
			doInLoop();
			if (this.interval > 0)
				waitEx(this.interval);
		}
		this.running = false;
	}

	protected abstract void doInLoop();

}
